const cors=require('cors')
const path=require('path')
const express= require('express')
const {expressjwt:expressJWT}=require('express-jwt')
const router=require('./router/user')
const userinfoRouter=require('./router/userInfo')
const {jwtConfig}=require('./utils/index')

// 导入 Joi 来定义验证规则
const Joi = require('joi')
const app=express()
 
app.use(cors())
app.use(express.urlencoded({extended:false}))
app.use(expressJWT({secret:jwtConfig.secret,algorithms:['HS256']}).unless({path:jwtConfig.unless}))
// app.use(express.static())

app.use((req,res,next)=>{
 res.interRes=function(err,status){
    res.send({
        status,
        message:err instanceof Error?err.message:err
    })
 }
 next()
})
app.use('/api',router)
app.use('/user',userinfoRouter)


// 4.1 错误级别中间件
app.use(function (err, req, res, next) {
    // 4.1 Joi 参数校验失败
    if (err instanceof Joi.ValidationError) {
      return res.send({
        status: 1,
        message: err.message
      })
    }
    // 4.2 未知错误
    res.send({
      status: 1,
      message: err.message
    })
  })
app.listen('3007',()=>{
    console.log('服务启动了， http://127.0.0.1:3007')
})